<!-- pages/merchant/goods-manage/goods-manage.vue -->
<template>
  <view class="goods-manage">
    <u-navbar
      backIconColor="#fff"
      :is-back="true"
      title-color="#fff"
      title="产品管理"
      :background="background"
      :border-bottom="false"
    />

    <view class="search-section">
      <u-search
        v-model="searchKeyword"
        :show-action="false"
        height="56"
        placeholder="搜索产品名称"
        @search="onSearch"
        @clear="onClear"
      />
    </view>

    <view class="filter-tabs">
      <view class="tab-item" :class="{ active: currentTab === 'all' }" @click="changeTab('all')">
        全部
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'for_sale' }"
        @click="changeTab('for_sale')"
      >
        出售中
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'in_warehouse' }"
        @click="changeTab('in_warehouse')"
      >
        已下架
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'sold_out' }"
        @click="changeTab('sold_out')"
      >
        售罄
      </view>
    </view>

    <scroll-view
      class="goods-list"
      scroll-y="true"
      @scrolltolower="loadMore"
      :style="{ height: `calc(100vh - ${statusBarHeight + navbarHeight + 120}px)` }"
    >
      <view v-for="(item, index) in goodsList" :key="item.id" class="goods-item">
        <view class="goods-content">
          <u-image
            :src="item.picUrl"
            width="160"
            height="160"
            border-radius="10"
            mode="aspectFill"
          />
          <view class="goods-info">
            <view class="goods-name">{{ item.name }}</view>
            <view class="goods-price">¥{{ (Number(item.price) * 0.01).toFixed(2) }}</view>
            <view class="goods-actions dis-flex">
              <view class="goods-status" :class="{ 'status-off': item.status !== 1 }">
                {{
                  item.status === 1
                    ? item.stock == 0
                      ? '补货中'
                      : '在售'
                    : item.status === -1
                      ? '已回收'
                      : '仓库中'
                }}
              </view>
              <view class="flex-1"></view>
              <view class="dis-flex" style="gap: 10rpx">
                <u-button
                  v-if="item.status === -1"
                  type="error"
                  size="mini"
                  @click="deleteGoods(item)"
                >
                  删除
                </u-button>
                <u-button
                  v-if="item.status === 0"
                  type="error"
                  size="mini"
                  @click="recycleGoods(item)"
                >
                  回收
                </u-button>
                <u-button
                  v-if="item.status !== -1"
                  type="warning"
                  size="mini"
                  :plain="item.status === 1"
                  @click="toggleStatus(item, index)"
                >
                  {{ item.status === 1 ? '下架' : '上架' }}
                </u-button>
                <u-button v-if="!item.specType" type="success" size="mini" @click="editGoods(item)">
                  编辑
                </u-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <u-loadmore :status="loadStatus" v-if="goodsList.length > 0" />

      <view v-if="goodsList.length === 0 && !loading" class="empty">
        <u-empty text="暂无产品数据" mode="list"></u-empty>
      </view>
    </scroll-view>

    <!-- 编辑产品弹窗 -->
    <u-popup
      v-model="showEditPopup"
      mode="bottom"
      width="750"
      height="auto"
      border-radius="20"
      :z-index="1000"
    >
      <view class="edit-popup">
        <view class="popup-header">
          <text class="title">{{ editingGoods.id ? '编辑产品' : '新增产品' }}</text>
          <u-icon name="close" size="36" @click="onEditPopupClose"></u-icon>
        </view>
        <scroll-view class="edit-content" scroll-y="true" style="max-height: 600rpx">
          <view class="form-item">
            <text class="label">产品名称（如：青椒肉沫）</text>
            <u-input
              v-model="editingGoods.name"
              type="text"
              :border="true"
              placeholder="请输入产品名称"
            />
          </view>
          <view class="form-item">
            <text class="label">产品分类</text>
            <view class="dis-flex" @click="showSpuCategoryPicker">
              <text style="color: #666; padding: 10rpx">{{ spuCategoryName }}</text>
              <view class="flex-1"></view>
              <u-icon name="arrow-down" color="#666"></u-icon>
            </view>
          </view>
          <view v-if="editingGoods.priceMode === 1" class="form-item">
            <text class="label">销售价格（元）</text>
            <u-input
              v-model="editingGoods.price"
              type="digit"
              :border="true"
              placeholder="请输入销售价格"
            />
          </view>
          <view class="form-item">
            <text class="label">计量单位（如：件、箱、克）</text>
            <u-input
              v-model="editingGoods.unitName"
              type="text"
              :border="true"
              placeholder="请输入计量单位"
            />
          </view>
          <view class="form-item">
            <text class="label">计量数值（如：50克）</text>
            <view class="dis-flex flex-x-baseline" style="padding: 20rpx; border: 1px solid #eee">
              <input
                class="flex-1"
                v-model="editingGoods.stepQuantity"
                type="number"
                placeholder="请输入计量数值"
              />
              <text class="tips">{{ editingGoods.unitName || '' }}</text>
            </view>
          </view>
          <view class="form-item">
            <text class="label">库存数量（如：999×50克）</text>
            <view class="dis-flex flex-x-baseline" style="padding: 20rpx; border: 1px solid #eee">
              <input
                class="flex-1"
                v-model="editingGoods.stock"
                type="number"
                placeholder="请输入库存数量"
              />
              <text class="tips"
                >×{{ editingGoods.stepQuantity }}{{ editingGoods.unitName || '' }}</text
              >
            </view>
          </view>
          <view class="form-item">
            <text class="label">封面图片</text>
            <view class="image-upload">
              <u-upload
                ref="uUpload"
                width="200"
                height="200"
                :action="action"
                :max-count="1"
                :max-size="2 * 1024 * 1024"
                :file-list="fileList"
                @on-uploaded="onUploadComplete"
                @on-remove="onImageRemove"
              ></u-upload>
            </view>
          </view>
          <view class="form-item">
            <text class="label">菜肴属性</text>
            <u-radio-group v-model="editingGoods.dishAttribute" active-color="#10a28f">
              <u-radio v-for="(item, index) in dishAttributes" :key="index" :name="index">
                {{ item }}
              </u-radio>
            </u-radio-group>
          </view>
        </scroll-view>
        <view class="popup-footer">
          <u-button
            type="success"
            :loading="saving"
            :custom-style="{ background: '#10a28f' }"
            @click="saveGoods"
          >
            保存
          </u-button>
        </view>
      </view>
    </u-popup>

    <u-select
      v-model="showSpuCategoryList"
      mode="single-column"
      :list="spuCategoryList"
      :default-value="[spuCategoryIndex]"
      @confirm="onSpuCategoryConfirm"
    ></u-select>

    <view class="add-btn" @click="addGoods">
      <u-icon name="plus" size="40" color="#fff"></u-icon>
    </view>
  </view>
</template>

<script>
import { BASE_URL, UP_URL } from '@/common/config'
import { dishAttributeMap } from '@/store/goods-list/dine-enums'

let systemInfo = uni.getSystemInfoSync()

export default {
  data() {
    return {
      background: {
        background: '#10A28F'
      },
      statusBarHeight: systemInfo.statusBarHeight,
      navbarHeight: 44,
      searchKeyword: '',
      shopId: '',
      currentTab: 'all',
      goodsList: [],
      loading: false,
      loadStatus: 'loadmore',
      page: 1,
      pageSize: 10,
      total: 0,
      showEditPopup: false,
      showSpuCategoryList: false,
      spuCategoryList: [],
      spuCategoryName: '请选择',
      spuCategoryIndex: 0,
      dishAttributes: dishAttributeMap,
      editingGoods: {
        id: null,
        name: '',
        categoryId: '',
        priceMode: 1,
        price: '',
        unitName: '克',
        stepQuantity: 50,
        stock: 0,
        picUrl: '',
        dishAttribute: 0,
        skus: []
      },
      action: BASE_URL + UP_URL,
      fileList: [],
      saving: false
    }
  },
  onLoad(options) {
    this.currentTab = options.tabType || 'all'
    this.shopId = options.shopId || ''
    this.loadGoodsList()
    this.loadSpuCategoryList()
  },
  methods: {
    // 搜索产品
    onSearch(_value) {
      this.page = 1
      this.goodsList = []
      this.loadGoodsList()
    },

    // 清空搜索
    onClear() {
      this.searchKeyword = ''
      this.page = 1
      this.goodsList = []
      this.loadGoodsList()
    },

    // 切换状态筛选
    changeTab(tab) {
      this.currentTab = tab
      this.page = 1
      this.goodsList = []
      this.loadGoodsList()
    },

    // 加载产品列表
    async loadGoodsList() {
      if (this.loading) return
      this.loading = true
      this.loadStatus = 'loading'
      try {
        const params = {
          pageNo: this.page,
          pageSize: this.pageSize
        }
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }
        if (this.currentTab !== '') {
          params.tabType = this.currentTab
        }
        const res = await this.$u.get('/app-api/product/spu/page-for-seller', params)
        if (res.code === 0) {
          const newGoods = res.data.list || []
          if (this.page === 1) {
            this.goodsList = newGoods
          } else {
            this.goodsList = [...this.goodsList, ...newGoods]
          }
          this.total = res.data.total
          this.loadStatus = this.goodsList.length < this.total ? 'loadmore' : 'nomore'
        }
      } catch (error) {
        console.error('加载产品列表失败:', error)
        this.$u.toast('加载产品列表失败')
      } finally {
        this.loading = false
      }
    },

    async loadSpuCategoryList() {
      try {
        const res = await this.$u.get('/app-api/product/category/list?shopId=' + this.shopId)
        if (res.code === 0) {
          this.spuCategoryList = []
          res.data.forEach((item) => {
            this.spuCategoryList.push({
              label: item.name,
              value: item.id
            })
          })
        }
      } catch (error) {
        console.error('加载产品分类失败:', error)
        this.$u.toast('加载产品分类失败')
      }
    },
    showSpuCategoryPicker() {
      this.showSpuCategoryList = true
    },
    selectDefaultSpuCategory() {
      this.spuCategoryName = '请选择'
      for (let i = 0, n = this.spuCategoryList.length; i < n; i++) {
        const item = this.spuCategoryList[i]
        console.log('item==' + JSON.stringify(item))
        if (item.value == this.editingGoods.categoryId) {
          this.spuCategoryName = item.label
          this.spuCategoryIndex = i
          break
        }
      }
    },
    onSpuCategoryConfirm(e) {
      //console.log(JSON.stringify(e))
      this.spuCategoryName = e[0].label
      this.editingGoods.categoryId = e[0].value
    },

    // 加载更多
    loadMore() {
      if (this.goodsList.length < this.total && this.loadStatus !== 'loading') {
        this.page++
        this.loadGoodsList()
      }
    },
    // 切换产品状态（上下架）
    async toggleStatus(item, index) {
      const newStatus = item.status === 1 ? 0 : 1
      const action = newStatus === 1 ? '上架' : '下架'
      uni.showModal({
        title: '温馨提示',
        content: `确定要${action}产品"${item.name}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const params = {
                id: item.id,
                status: newStatus
              }
              const result = await this.$u.post('/app-api/product/spu/update-status', params)
              if (result.code === 0) {
                this.$u.toast(`${action}成功`)
                this.goodsList[index].status = newStatus
              } else {
                this.$u.toast(result.msg || `${action}失败`)
              }
            } catch (error) {
              console.error(`${action}失败:`, error)
              this.$u.toast(`${action}失败`)
            }
          }
        }
      })
    },

    onEditPopupClose() {
      this.showEditPopup = false
      this.fileList = []
      this.$refs.uUpload?.clear()
    },
    // 添加产品
    addGoods() {
      this.editingGoods = {
        id: null,
        name: '',
        categoryId: '',
        priceMode: 1,
        price: '',
        unitName: '克',
        stepQuantity: 50,
        stock: 0,
        picUrl: '',
        dishAttribute: 0
      }
      this.fileList = []
      this.showEditPopup = true
      this.selectDefaultSpuCategory()
    },

    // 编辑产品
    editGoods(item) {
      this.editingGoods = {
        id: item.id,
        name: item.name,
        categoryId: item.categoryId,
        priceMode: item.priceMode,
        price: (Number(item.price) * 0.01).toFixed(2),
        unitName: item.unitName,
        stepQuantity: item.stepQuantity,
        stock: item.stock,
        picUrl: item.picUrl,
        dishAttribute: item.dishAttribute,
        skus: item.skus
      }
      this.fileList = [
        {
          url: item.picUrl,
          status: 'success'
        }
      ]
      this.showEditPopup = true
      this.selectDefaultSpuCategory()
    },

    // 回收产品
    recycleGoods(item) {
      uni.showModal({
        title: '温馨提示',
        content: `确定要将产品"${item.name}"放到回收站吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const action = '回收'
              const newStatus = -1
              const params = {
                id: item.id,
                status: newStatus
              }
              const result = await this.$u.post('/app-api/product/spu/update-status', params)
              if (result.code === 0) {
                this.$u.toast(`${action}成功`)
                this.goodsList[index].status = newStatus
              } else {
                this.$u.toast(result.msg || `${action}失败`)
              }
            } catch (error) {
              console.error(`${action}失败:`, error)
              this.$u.toast(`${action}失败`)
            }
          }
        }
      })
    },
    // 删除产品
    deleteGoods(item) {
      uni.showModal({
        title: '温馨提示',
        content: `确定要删除产品"${item.name}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await this.$u.get('/app-api/product/spu/delete?id=' + item.id)
              this.page = 1
              this.goodsList = []
              this.loadGoodsList()
            } catch (error) {
              console.error(`删除失败:`, error)
              this.$u.toast(`删除失败`)
            }
          }
        }
      })
    },
    // 上传图片完成
    onUploadComplete(list) {
      if (list.length > 0 && list[0].response) {
        this.editingGoods.picUrl = list[0].response.data
      }
    },
    // 移除图片
    onImageRemove(_index, _list) {
      this.editingGoods.picUrl = ''
    },

    // 保存产品
    async saveGoods() {
      if (!this.editingGoods.name) {
        this.$u.toast('请输入产品名称')
        return
      }
      if (!this.editingGoods.price) {
        this.$u.toast('请输入销售价格')
        return
      }
      if (!this.editingGoods.picUrl) {
        this.$u.toast('请上传封面图')
        return
      }
      this.saving = true
      try {
        const params = Object.assign({}, this.editingGoods)
        params.price = parseFloat(this.editingGoods.price) * 100 // 转换为分
        let result
        if (params.id) {
          // 编辑产品
          result = await this.$u.post('/app-api/product/spu/update-basic', params)
        } else {
          // 新增产品
          result = await this.$u.post('/app-api/product/spu/create-basic', params)
        }
        if (result.code === 0) {
          this.$u.toast(this.editingGoods.id ? '编辑成功' : '新增成功')
          this.showEditPopup = false
          // 重新加载列表
          this.page = 1
          this.goodsList = []
          this.loadGoodsList()
        } else {
          this.$u.toast(result.msg || (this.editingGoods.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('保存产品失败:', error)
        this.$u.toast(this.editingGoods.id ? '编辑失败' : '新增失败')
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-manage {
  background: #f5f5f5;
  min-height: 100vh;

  .search-section {
    padding: 20rpx;
    background: #fff;
  }

  .filter-tabs {
    display: flex;
    background: #fff;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 15rpx 0;
      font-size: 28rpx;
      color: #666;
      border-radius: 10rpx;

      &.active {
        background: #10a28f;
        color: #fff;
      }
    }
  }

  .goods-list {
    padding: 20rpx;

    .goods-item {
      background: #fff;
      border-radius: 10rpx;
      margin-bottom: 20rpx;
      padding: 20rpx;

      .goods-content {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .goods-info {
          flex: 1;
          margin-left: 20rpx;

          .goods-name {
            font-size: 30rpx;
            color: #333;
            margin-bottom: 10rpx;
            font-weight: 500;
          }

          .goods-price {
            font-size: 28rpx;
            color: #fa453c;
            margin-bottom: 10rpx;
            font-weight: 600;
          }

          .goods-status {
            font-size: 24rpx;
            color: #10a28f;

            &.status-off {
              color: #999;
            }
          }
        }
      }

      .goods-actions {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
      }
    }

    .empty {
      text-align: center;
      padding: 100rpx 0;
    }
  }

  .edit-popup {
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      border-bottom: 1rpx solid #eee;

      .title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .edit-content {
      padding: 20rpx;

      .form-item {
        margin-bottom: 30rpx;

        .label {
          display: block;
          margin-bottom: 15rpx;
          font-size: 28rpx;
          color: #333;
        }

        .image-upload {
          margin-top: 15rpx;
        }
      }
    }

    .popup-footer {
      padding: 20rpx;
      border-top: 1rpx solid #eee;
    }
  }

  .add-btn {
    position: fixed;
    right: 40rpx;
    bottom: 40rpx;
    width: 100rpx;
    height: 100rpx;
    background: #10a28f;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 20rpx rgba(16, 162, 143, 0.3);
    z-index: 2;
  }
}
</style>
